﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RepositoryWithHistory.cs" company="emrecoskun.net">
//   ecblog.codeplex.com - emrecoskun.net
// </copyright>
// <summary>
//   The reposository with history
// </summary>
// --------------------------------------------------------------------------------------------------------------------
 
namespace EcBlog.Data.Sql.Base
{
    using AutoMapper;

    using EcBlog.Data.Base;
    using EcBlog.Models;

    /// <summary>
    /// The reposository with history 
    /// </summary>
    /// <typeparam name="TEntity">The type of the entity.</typeparam>
    /// <typeparam name="THistoryEntity">The type of the history entity.</typeparam>
    public abstract class RepositoryWithHistory<TEntity, THistoryEntity> : Repository<TEntity>
        where TEntity : class where THistoryEntity : class
    {
        /// <summary>
        /// The history repository.
        /// </summary>
        private readonly IHistoryRepository<THistoryEntity> historyRepository;

        /// <summary>
        /// Initializes a new instance of the <see cref="RepositoryWithHistory&lt;TEntity, THistoryEntity&gt;"/> class.
        /// </summary>
        /// <param name="context">The context.</param>
        protected RepositoryWithHistory(TransactionalDbContext context) : base(context)
        {
            this.historyRepository = new HistoryRepository<THistoryEntity>(context);
        }

        /// <summary>
        /// Creates the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        public override void Create(TEntity entity)
        {
            base.Create(entity);
            this.historyRepository.Insert(() => Mapper.Map<THistoryEntity>(entity), CrudOperation.Create);
        }

        /// <summary>
        /// Updates the specified entity to update.
        /// </summary>
        /// <param name="entityToUpdate">The entity to update.</param>
        public override void Update(TEntity entityToUpdate)
        {
            base.Update(entityToUpdate);
            this.historyRepository.Insert(() => Mapper.Map<THistoryEntity>(entityToUpdate), CrudOperation.Update);
        }

        /// <summary>
        /// Deletes the specified entity to delete.
        /// </summary>
        /// <param name="entityToDelete">The entity to delete.</param>
        public override void Delete(TEntity entityToDelete)
        {
            base.Delete(entityToDelete);
            this.historyRepository.Insert(() => Mapper.Map<THistoryEntity>(entityToDelete), CrudOperation.Delete);
        }
    }
}